<template>
    <nly-content-wrapper>
        <nly-content-header>
            <section>
                <div class="big-main-wrapper" style="border-bottom:0px;margin:0px;">
                    <div class="btn-wrapper clearfix" style="margin-bottom:0">
                        <a-row class="text-center clearfix">
                            <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                                <a-col v-if="permissions.includes('user:changeManager')" :span="3">
                                    <div class="btns" @click="updateSysManager">
                                        <a-icon class="btns-icon" type="solution" />
                                        <div class="btns-text" title="更换系统管理员">更换系统管理员</div>
                                    </div>
                                </a-col>
                                <!-- <a-col v-if="permissions.includes('user:restPassword')" :span="2">
                                    <div class="btns" @click="resetPassword">
                                        <a-icon class="btns-icon" type="lock" />
                                        <div class="btns-text" title="重置密码">重置密码</div>
                                    </div>
                                </a-col> -->
                                <a-col :span="2">
                                    <div class="btns" @click="dimissionHandler">
                                        <a-icon class="btns-icon" type="lock" />
                                        <div class="btns-text" title="离职">离职</div>
                                    </div>
                                </a-col>
                                <a-col v-if="permissions.includes('user:inviteIn')" :span="2">
                                    <div class="btns" @click="userEntry">
                                        <a-icon class="btns-icon" type="share-alt" />
                                        <div class="btns-text" title="邀请入职">邀请入职</div>
                                    </div>
                                </a-col>
                                <!-- <a-col :span="2">
                                    <div class="btns" @click="AddUser">
                                        <a-icon class="btns-icon" type="share-alt" />
                                        <div class="btns-text" title="添加用户">添加用户</div>
                                    </div>
                                </a-col> -->
                                <!-- <a-col :span="1" style="text-align:center">
                                    <div style="border:1px solid #888;height:32px;width:2px;margin:0 auto;">

                                    </div>
                                </a-col>
                                <a-col :span="2">
                                    <div class="btns" @click="PageListUser">
                                        <a-icon class="btns-icon" type="file-search" />
                                        <div class="btns-text">查询</div>
                                    </div>
                                </a-col> -->
                                <!-- <a-col :span="2">
                                    <div class="btns" @click="reset">
                                        <a-icon class="btns-icon" type="undo" />
                                        <div class="btns-text">重置</div>
                                    </div>
                                </a-col> -->
                            </a-col>
                        </a-row>
                    </div>
                </div>
                <!-- </nly-col> -->
                <!-- <nly-col xs="12" sm="12" md="12" lg="3" xl="3" class="form-inline align-self-start " style="justify-content: right;">

                        <nly-button-group>
                            <nly-button variant="info" @click="PageListUser" button-class="mr-2">查询</nly-button>
                            <nly-button variant="info" button-class="mr-2" @click="reset">重置</nly-button>
                            <nly-button @click="showFunction" variant="info" button-class="mr-2">
                                <nly-icon :icon="show ? 'fas fa-angle-down mr-1' : 'fas fa-angle-up mr-1'" />
                                {{ show ? "折叠" : "展开" }}
                            </nly-button>
                        </nly-button-group>
                    </nly-col> -->
                <!-- </nly-row> -->

            </section>
        </nly-content-header>
        <div style="height:100%;margin:0 0.5rem;border:1px solid #ccc;border-top:none">
            <div style="float: left;width: 200px;margin-right:5px;border-right:1px solid #ccc;height:100%;">
                <div class="organization">
                    组织机构
                </div>
                <div style="overflow-y:auto;height:calc(100% - 60px);">
                    <a-tree :expanded-keys="expandedOfficeKeys" :tree-data="officeTreeData" @expand="onOfficeExpand" @select="onSelect" :show-line="true" />
                </div>
            </div>
            <div>
                <!-- <a-button type="primary" class="crm-btn" @click="updateSysManager" button-class="mr-2">更换系统管理员</a-button> -->
                <!-- <a-button type="primary" class="crm-btn" @click="resetPassword" button-class="mr-2">重置密码</a-button> -->
                <!-- <a-button type="primary" class="crm-btn" @click="AddUser" button-class="mr-2">添加用户</a-button> -->
                <!-- <a-button type="primary" class="crm-btn" @click="userEntry" button-class="mr-2">邀请入职</a-button> -->
                <!-- user table列表 -->
                <div style="margin:10px 0;">
                    <span style="">登录账号: </span>
                    <a-input style="width:120px;" v-model="postData.userName"></a-input>
                    <span style="margin-left:10px;">用户姓名: </span>
                    <a-input style="width:120px;" v-model="postData.realName"></a-input>
                    <!-- <input-group-search title="所属机构"  modalTitle="选择机构" rightStyle="width: 150px;"  treeType="office" v-model="postData.officeId"></input-group-search> -->
                    <span style="margin-left:10px;">状态: </span>
                    <a-select default-value="0" style="width: 120px;top:-3px;" @change="handleChange">
                        <a-select-option value>全部</a-select-option>
                        <a-select-option value="0">正常</a-select-option>
                        <a-select-option value="2">停用</a-select-option>
                    </a-select>
                    <a-button style="top:-2px;margin-left:10px;" type="primary" @click="PageListUser">
                        查询
                    </a-button>
                </div>
                <a-table :columns="columns" :data-source="data" bordered :scroll="{ x: 1000, y: 500}" :pagination="pagination" :row-selection="{selectedRowKeys: selectedKeys, onChange: userSelection}" @change="onTableChange" style="height: calc(100vh - 14rem);"></a-table>
            </div>
        </div>
        <nly-content>
            <!-- 邀请入职 -->
            <a-modal v-model="entryVisible" title="邀请入职" :footer="null" centered on-ok="handleok" width="650px">
                <a-form :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }" class="user-class">
                    <a-form-item label="入职网址">
                        <a-input-search v-model="entryUrl" read-only style="width: 475px" @search="onCopy">
                            <a-button slot="enterButton">复制</a-button>
                        </a-input-search>
                    </a-form-item>
                    <a-form-item label="入职二维码">
                        <div class="qrcode" id="qrcode" ref="qrCodeUrl"></div>
                        <a href="javascript:;" title="下载二维码" class="mr-1" @click="downloadQrCode">点击下载</a>
                    </a-form-item>
                </a-form>
            </a-modal>
            <!-- modal用户编辑 弹窗  -->
            <a-modal v-model="editModal" centered :title="editItem.id ? '编辑用户' : '新增用户'" width="900px">
                <div id="components-form-demo-advanced-search">
                    <a-form class="ant-advanced-search-form" :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 24 }" @submit="handleSubmit">
                        <div class="line" style="color:#1980Ff;font-size:15px;">基本信息</div>
                        <a-row :gutter="24">
                            <a-col :span="10">
                                <a-form-item label="登录账号">
                                    <a-input v-decorator="['userName', { rules: [{ required: true, message: '登录账号不能为空' }] }]" placeholder="请输入手机号" :disabled="isDisabled" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="10" :push="2">
                                <a-form-item label="手机号码">
                                    <a-input v-decorator="['mobile', { rules: [{ required: false, message: '手机号码不能为空' }] }]" placeholder="请输入手机号码" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="10">
                                <a-form-item label="用户姓名">
                                    <a-input v-decorator="['realName', { rules: [{ required: true, message: '用户姓名不能为空' }] }]" placeholder="请输入用户姓名" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="10" :push="2">
                                <a-form-item label="*所属机构" :validate-status="validateStatus" :help="errorMsg">
                                    <a-input-search :value="parentName" placeholder="请选择机构" @click="selectOffice" @search="selectOffice" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="10">
                                <a-form-item label="职务">
                                    <a-input v-decorator="['duty', { rules: [{ required: false, message: '职务不能为空' }] }]" placeholder="请输入职务" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="10" :push="2">
                                <a-form-item label="电子邮箱">
                                    <a-input v-decorator="['email', { rules: [{ required: false, message: '电子邮箱不能为空' }] }]" placeholder="请输入电子邮箱" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24" :style="isShow">
                            <a-col :span="10">
                                <a-form-item label="登录密码">
                                    <a-input v-decorator="['password', { rules: [{ required: false, message: '密码不能为空' }] }]" placeholder="请输入登录密码" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="22" :pull="3">
                                <a-form-item label="备注">
                                    <a-textarea placeholder="请输入用户备注" :rows="5" v-decorator="['remarks', { rules: [{ required: false, message: '' }] }]" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <div v-show="isRoleTableShow">
                            <div class="line" style="color:#1980Ff;font-size:15px;">分配角色</div>
                            <a-table :columns="roleColumns" :data-source="roleData" bordered style="font-size: 12px;min-height: 200px;" :row-selection="{selectedRowKeys: selectedRowKeys, onChange: roleSelection}" :pagination="false"></a-table>
                        </div>
                    </a-form>
                </div>
                <template slot="footer">
                    <a-button type="primary" html-type="submit" @click="handleSubmit" v-if="permissions.includes('user:save')">保存</a-button>
                    <a-button :style="{ marginLeft: '8px' }" @click="handleReset">重置</a-button>
                    <a-button :style="{ marginLeft: '8px' }" @click="hideModal">关闭</a-button>
                </template>
            </a-modal>
            <!-- modal分配角色弹窗  -->
            <a-modal v-model="roleModal" centered title="分配角色" width="650px" @cancel="hideModal">
                <div id="components-form-demo-advanced-search">
                    <div class="line" style="color:#1980Ff;font-size:15px;">分配角色</div>
                    <a-table :columns="roleColumns" :data-source="roleData" bordered style="font-size: 12px;min-height: 200px;" :row-selection="{selectedRowKeys: selectedRowKeys, onChange: roleSelection,columnWidth:20}" :pagination="false"></a-table>
                </div>
                <template slot="footer">
                    <a-button type="primary" @click="saveUserRole">保存</a-button>
                    <a-button :style="{ marginLeft: '8px' }" @click="hideModal">关闭</a-button>
                </template>
            </a-modal>
            <a-modal :visible="officeModal" lg :footer="null" title="机构选择" size="sm" @cancel="hideOfficeModal">
                <div style="height: 400px;overflow-y:scroll;">
                    <a-input-search style="margin-bottom: 8px" placeholder="机构名称" @change="onChange" />
                    <a-tree :expanded-keys="expandedOfficeKeys" :selected-keys="selectedOfficeKeys" :tree-data="officeTreeData" @expand="onOfficeExpand" @select="onOfficeSelect" :show-line="true" />
                </div>
                <a-row>
                    <a-col :span="24" :style="{ textAlign: 'right' }">
                        <a-button type="primary" html-type="submit" @click="saveOffice">保存</a-button>
                        <a-button :style="{ marginLeft: '8px' }" @click="hideOfficeModal">关闭</a-button>
                    </a-col>
                </a-row>
            </a-modal>
        </nly-content>
    </nly-content-wrapper>
</template>

<script>

import { mapState } from "vuex";
import { FormInput, EditableCell } from "@/components/Form";
import { PageListUser, Save, Delete, ResetPassword, UpdateSysManager, SaveUserRole } from "@/api/user";
import { RoleList, CheckRoleId } from "@/api/role";
import { PageList } from "@/api/office";
import { getCompanyInfo } from "@/api/companyInfo";
import { constantRouterComponentsKeys } from "@/router/generator-routers";
import QRCode from "qrcodejs2";
import VueClipboard from "vue-clipboard2";

import { byebye } from "@/api/personal/userInfo";
import Vue from "vue";
Vue.use(VueClipboard);

let keyMap = new Map();

/**
 * 机构数组转树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
const listToTree = (list, tree, parentId) => {
    list.forEach(item => {
        // 判断是否为父级菜单
        if (item.parentId === parentId) {
            let officeName = item.officeName;
            if (item.officeCode != null && item.officeCode.length > 0) {
                officeName = item.officeName + "(" + item.officeCode + ")";
            }
            const child = {
                ...item,
                key: item.id,
                title: officeName,
                children: []
            };
            // 迭代 list， 找到当前菜单相符合的所有子菜单
            listToTree(list, child.children, item.id);
            // 删掉不存在 children 值的属性
            if (child.children.length <= 0) {
                delete child.children;
            }
            // 加入到树中
            tree.push(child);
        }
    });
};

//获取父级key
const getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
            if (node.children.some(item => item.key === key)) {
                parentKey = node.key;
            } else if (getParentKey(key, node.children)) {
                parentKey = getParentKey(key, node.children);
            }
        }
    }
    return parentKey;
};

export default {
    props: {
        dataList: {
            type: Array,
            default: () => []
        }
    },
    components: {
        FormInput,
        EditableCell
    },
    data () {
        const roleColumns = [
            //角色信息table
            {
                title: "角色名称",
                dataIndex: "roleName",
                width: 60
            },
            {
                title: "角色描述",
                dataIndex: "remarks",
                width: 120,
                ellipsis: true,
            }
        ];
        const columns = [
            //用户信息table
            {
                align: "left",
                title: "登录账号",
                dataIndex: "userName",
                width: "120"
            },
            {
                align: "left",
                title: "用户姓名",
                dataIndex: "realName",
                width: "120"
            },
            {
                align: "left",
                title: "所属机构",
                dataIndex: "officeName",
                width: "120"
            },
            {
                align: "left",
                title: "角色名称",
                dataIndex: "roleName",
                width: "120"
            },
            {
                align: "left",
                title: "手机号",
                dataIndex: "mobile",
                width: "120"
            },
            {
                align: "left",
                title: "电子邮箱",
                dataIndex: "email",
                width: "120"
            },
            {
                align: "left",
                title: "备注",
                dataIndex: "remarks",
                width: "120"
            },
            {
                align: "left",
                title: "状态",
                dataIndex: "status",
                width: "120",
                customRender: (text, row, index) => {
                    return text == 2 ? (
                        <nly-badge bg-variant="danger">停用</nly-badge>
                    ) : (
                        <nly-badge bg-variant="success">正常</nly-badge>
                    );
                }
            },
            {
                title: "操作",
                dataIndex: "o",
                width: "200",
                customRender: (text, row, index) => {
                    const { permissions } = this;
                    // if (row.id != 1 && !row.isSysAdmin)
                    return (
                        <div class="icons-list">
                            {permissions.includes('user:edit') ? <a
                                href="javascript:;"
                                title="编辑用户"
                                class="mr-1"
                                onClick={() => this.showModal(row)}
                            >
                                <a-icon type="edit" theme="twoTone" />
                            </a> : null}
                            {permissions.includes('user:enable') && row.id != 1 && !row.isSysAdmin ? (
                                <span>
                                    {row.status == 0 ? (
                                        <a
                                            href="javascript:;"
                                            title="禁用用户"
                                            class="mr-1 "
                                            onClick={() => this.updateUser(row)}
                                        >
                                            <a-icon
                                                type="stop"
                                                theme="twoTone"
                                                two-tone-color="red"
                                            />
                                        </a>
                                    ) : (
                                        <a
                                            href="javascript:;"
                                            title="启用用户"
                                            class="mr-1 "
                                            onClick={() => this.updateUser(row)}
                                        >
                                            <a-icon
                                                type="check-circle"
                                                theme="twoTone"
                                                two-tone-color="#52c41a"
                                            />
                                        </a>
                                    )}

                                    <a href="javascript:;" title="删除用户" class="mr-1" onClick={() => this.deleteSysUser(row)}></a>
                                    {permissions.includes('user:assignrole') ? <a href="javascript:;" title="分配角色" class="mr-1" onClick={() => this.updateRole(row)}>分配角色</a> : null}

                                </span>) : (
                                <span></span>
                            )}
                        </div>
                    );
                }
            }
        ];

        const treeData = [];

        return {
            isShow: "display:block",
            editModal: false,
            officeModal: false,
            roleModal: false,
            isDisabled: false,
            entryVisible: false, //入职弹窗
            entryUrl: "", //入职链接
            autoExpandParent: true,
            expandedOfficeKeys: [],
            checkedOfficeKeys: [], //office tree默认选中的key
            selectedOfficeKeys: [],
            dataScope: "1",
            parentName: "", //上级id
            parentId: [], //上级机构名称
            treeData,
            qrCodeFlag: false,
            officeTreeData: [],
            form: this.$form.createForm(this, { name: "advanced_search" }),
            formLayout: "horizontal",
            expand: false,
            postData: {
                "page.current": 1,
                "page.size": 20,
                userName: "",
                realName: "",
                status: "",
                officeId: null
            },
            pagination: {
                defaultPageSize: 20,
                current: 1,
                pageSize: 20,
                total: 0,
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input-number
                                value={this.pagination.pageSize}
                                min={1}
                                max={500}
                                onPressEnter={e => this.changePageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                showQuickJumper: true,
                showLessItems: true
            },
            numberReg: /^[1-9]{1}[0-9]*$/,
            floatReg: /^-?[0-9]*(\.[0-9]*)?$/,
            data: [],
            roleData: [],
            columns,
            roleColumns,
            validateStatus: "success",
            errorMsg: null,
            show: false, //是否显示弹窗
            editItem: {}, //新增/编辑对象
            TreeSortEditList: new Map(), //菜单排序修改集合
            selectedRowKeys: [], //角色table选中key
            selectedKeys: [], //用户table选中key
            isRoleTableShow: true //是否显示
        };
    },
    mounted () {
        this.PageListUser();
        this.getCompanyInfo();
        this.getOfficeTreeData();
    },
    computed: {
        componentSelectList: function () {
            const dataList = new Array();
            constantRouterComponentsKeys().forEach(item => {
                dataList.push({ key: item, title: item });
            });
            return dataList;
        },
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
        }),
    },
    methods: {
        changePageSize (e) {
            const value = e.target.value;
            const { pagination } = this;

            console.log(e, value);
            Object.assign(this.postData, {
                "page.size": value
            });
            Object.assign(this.pagination, {
                pageSize: Number.parseInt(value)
            });
            this.PageListUser();
        },
        roleSelection (keys) {
            console.log(keys);
            this.selectedRowKeys = [];
            this.selectedRowKeys = keys;
            console.log("rowKeys", this.selectedRowKeys);
        },
        userSelection (keys) {
            this.selectedKeys = [];
            this.selectedKeys = keys;
            console.log("rowKeys", this.selectedKeys);
        },
        hideModal () {
            this.editModal = false;
            this.roleModal = false;
        },
        hideOfficeModal () {
            this.officeModal = false;
        },
        //选择机构保存
        saveOffice () {
            this.officeModal = false;
            this.parentId = this.selectedOfficeKeys;
            this.parentName = keyMap.get(this.parentId[0]);
            if (this.parentName != null) {
                this.validateStatus = "success";
                this.errorMsg = null;
            }
        },
        //获取公司入职信息
        getCompanyInfo () {
            getCompanyInfo().then(response => {
                if (response.code == 200) {
                    this.entryUrl = response.data.entryUrl;
                }
            });
        },
        //邀请入职
        userEntry () {
            this.entryVisible = true;
            if (!this.qrCodeFlag) {
                setTimeout(() => {
                    this.creatQrCode();
                }, 100);
                this.qrCodeFlag = true;
            }
        },
        //添加
        AddUser () {
            this.expandedKeys = [];
            this.expandedOfficeKeys = [];
            this.checkedOfficeKeys = [];
            this.selectedRowKeys = [];
            this.editItem = {};
            this.isShow = "display:block";
            this.isDisabled = false;
            this.isRoleTableShow = true;
            console.log("roleList");
            RoleList().then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    this.roleData = data;
                }
            });
            this.form = this.$form.createForm(this, {
                mapPropsToFields: () => {
                    return {
                        password: this.$form.createFormField({
                            value: "123456"
                        })
                    };
                }
            });

            this.editModal = true;
        },
        //删除
        deleteSysUser (user) {
            let _this = this;
            this.$confirm({
                title: '提示',
                content: '您确定要删除该用户吗？',
                onOk () {
                    Delete({ id: user.id })
                        .then(response => {
                            if (response.code === 200) {
                                _this.$message.success("删除成功");
                                //刷新 列表
                                _this.PageListUser();
                            }
                        });
                },
                onCancel () {
                },
            });
        },
        //停用/启用用户
        updateUser (user) {
            let msg = user.status == 0 ? "停用" : "启用";
            let _this = this;
            this.$confirm({
                title: '提示',
                content: '您确定要' + msg + '该用户吗？',
                onOk () {
                    Save({
                        id: user.id,
                        status: user.status == 2 ? 0 : 2
                    })
                        .then(response => {
                            if (response.code === 200) {
                                _this.$message.success(msg + "成功");
                                //刷新 列表
                                _this.PageListUser();
                            }
                        });
                },
                onCancel () {
                },
            });
        },
        // 获取用户列表
        PageListUser () {
            const { postData } = this;
            PageListUser(postData)
                .then(response => {
                    console.log("获取用户列表", response);
                    if (response.code === 200) {
                        const { data } = response;
                        const { records, total, current, size } = data;
                        this.data = records;
                        Object.assign(this.pagination, {
                            total
                        });
                    }
                })
                .catch(error => { });
        },
        //获取系统用户
        showFunction () {
            this.show = !this.show;
        },
        //编辑用户
        showModal (editItem) {
            console.log("editItem", editItem);
            this.expandedKeys = [];
            this.editItem = { ...editItem };
            this.parentId = [this.editItem.officeId];
            this.parentName = this.editItem.officeName;
            this.isShow = "display:none";
            this.isDisabled = true;
            if (editItem.isSysAdmin) {
                this.isRoleTableShow = false;
            } else {
                this.isRoleTableShow = true;
            }
            this.form = this.$form.createForm(this, {
                mapPropsToFields: () => {
                    return {
                        userName: this.$form.createFormField({
                            value: this.editItem.userName
                        }),
                        password: this.$form.createFormField({
                            value: this.editItem.password
                        }),
                        realName: this.$form.createFormField({
                            value: this.editItem.realName
                        }),
                        remarks: this.$form.createFormField({
                            value: this.editItem.remarks
                        }),
                        email: this.$form.createFormField({
                            value: this.editItem.email
                        }),
                        mobile: this.$form.createFormField({
                            value: this.editItem.mobile
                        })
                    };
                }
            });
            RoleList().then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    this.roleData = data;
                    CheckRoleId({ userId: this.editItem.id }).then(response => {
                        if (response.code === 200) {
                            console.log(response.data);
                            this.selectedRowKeys = response.data;
                        }
                    });
                }
            });
            this.editModal = true;
        },
        updateRole (user) {
            this.editItem = { ...user };
            RoleList().then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    this.roleData = data;
                    CheckRoleId({ userId: user.id }).then(response => {
                        if (response.code === 200) {
                            console.log(response.data);
                            this.selectedRowKeys = response.data;
                        }
                    });
                }
            });
            this.roleModal = true;
        },
        //保存用户角色
        saveUserRole () {
            SaveUserRole({
                id: this.editItem.id,
                roleId: this.selectedRowKeys
            }).then(response => {
                if (response.code == 200) {
                    this.$message.success("保存成功");
                    this.roleModal = false;
                    this.PageListUser();
                }
            });
        },
        reset () {
            this.postData = {};
        },
        onTableChange (pagination, filters, sorter) {
            Object.assign(this.postData, {
                "page.current": pagination.current,
                "page.size": pagination.pageSize
            });
            Object.assign(this.pagination, {
                current: pagination.current,
                pageSize: pagination.pageSize
            });
            this.PageListUser();
        },
        onCellChange (item, dataIndex, editValue) {
            if (item[dataIndex] != editValue) {
                const edit = { id: item.id, [dataIndex]: editValue };
                this.TreeSortEditList.set(item.id, edit);
            } else {
                this.TreeSortEditList.delete(item.id);
            }
            console.log([...this.TreeSortEditList.values()]);
        },
        handleSubmit (e) {
            //用户保存提交
            e.preventDefault();
            this.form.validateFields((err, values) => {
                let id = this.editItem.id;
                this.editItem = { ...values };
                this.editItem.id = id;
                this.editItem.officeName = this.parentName;
                this.editItem.officeId = this.parentId[0];
                this.editItem.roleId = this.selectedRowKeys;
                if (this.parentName == null || this.parentName.length < 1) {
                    this.validateStatus = "error";
                    this.errorMsg = "机构不能为空";
                    return;
                }
                console.log("开始保存:", err);
                if (!err) {
                    Save(this.editItem)
                        .then(response => {
                            console.log(response)
                            if (response.code === 200) {
                                this.$message.success("保存成功");
                                //刷新 列表
                                this.PageListUser();
                                this.hideModal();
                            }
                        })
                }
            });
        },
        handleReset () {
            this.form.resetFields();
        },
        toggle () {
            this.expand = !this.expand;
        },
        //选择机构
        selectOffice () {
            this.officeModal = true;
        },
        getOfficeTreeData () {
            PageList()
                .then(response => {
                    if (response.code === 200) {
                        console.log("获取机构列表===111", response.data);
                        const { data } = response;
                        const childrenNav = [];
                        let keys = [];
                        for (let i = 0; i < data.length; i++) {
                            const node = data[i];
                            const key = node.id;
                            const title = node.officeName;
                            this.dataList.push({ key, title });
                            keys.push(key);
                            keyMap.set(key, title);
                        }
                        console.log("childrenOffice==");
                        listToTree(response.data, childrenNav, 0);
                        console.log("childrenOffice==");
                        this.officeTreeData = childrenNav;
                        this.expandedOfficeKeys = keys;
                        this.selectedOfficeKeys = this.parentId;
                    }
                })
                .catch(error => { });
        },
        //状态change
        handleChange (value) {
            this.postData.status = value;
            this.PageListUser();
        },
        //以下为dataTree 事件触发
        onOfficeExpand (expandedOfficeKeys) {
            console.log("onExpand", expandedOfficeKeys);
            this.expandedOfficeKeys = expandedOfficeKeys;
            this.autoExpandParent = false;
        },
        onOfficeCheck (checkedOfficeKeys) {
            console.log("onCheck", checkedOfficeKeys);
            this.checkedOfficeKeys = checkedOfficeKeys;
        },
        onOfficeSelect (selectedOfficeKeys, info) {
            console.log("onSelect", info.node.title);
            this.selectedOfficeKeys = selectedOfficeKeys;
        },
        onSelect (key, info) {
            this.postData.officeId = key[0];
            this.PageListUser();
        },
        onChange (e) {
            //tree 搜索
            const value = e.target.value;
            console.log(this.dataList);
            const expandedOfficeKeys = this.dataList
                .map(item => {
                    if (item.title.indexOf(value) > -1) {
                        return getParentKey(item.key, this.officeTreeData);
                    }
                    return null;
                })
                .filter((item, i, self) => item && self.indexOf(item) === i);
            Object.assign(this, {
                expandedOfficeKeys,
                searchValue: value,
                autoExpandParent: true
            });
        },
        //更换管理员
        updateSysManager () {
            if (this.selectedKeys.length != 1) {
                this.$message.warn("请选择一位用户");
                return false;
            } else {
                let _this = this;
                this.$confirm({
                    title: '提示',
                    content: '您确定要更换他为系统管理员？',
                    onOk () {
                        UpdateSysManager({ userId: _this.selectedKeys[0] }).then(
                            response => {
                                if (response.code === 200) {
                                    console.log("更换系统管理员成功，请重新登录");
                                    _this.$message.success("更换管理员成功");
                                    _this.$store.dispatch("Logout").then(() => {
                                        _this.$router.push({ path: "login" });
                                    });
                                }
                            }
                        );
                    },
                    onCancel () {
                    },
                });
            }
        },
        //重置密码
        resetPassword () {
            console.log(this.selectedKeys);
            if (this.selectedKeys.length <= 0) {
                this.$message.warn("请选择用户");
            } else {
                let _this = this;
                this.$confirm({
                    title: '提示',
                    content: '您确定要重置密码为123456？',
                    onOk () {
                        ResetPassword({
                            userId: _this.selectedKeys,
                            password: "123456"
                        }).then(response => {
                            if (response.code == 200) {
                                _this.selectedKeys = [];
                                _this.$message.success("重置密码成功");
                            }
                        });
                    },
                    onCancel () {
                    },
                });
            }
        },
        //离职
        dimissionHandler () {
            if (this.selectedKeys.length != 1) {
                this.$message.warn("请选择一位用户");
                return false;
            } else {
                let _this = this;
                this.$confirm({
                    title: '提示',
                    content: '您确定要离职选择的员工吗？',
                    onOk () {
                        byebye({ userId: _this.selectedKeys[0] }).then(res => {
                            if (res.code === 200) {
                                _this.$message.success('离职成功');
                                if (_this.selectedKeys[0] == _this.userInfo.id) {
                                    _this.$message.success('离职成功,请重新登录');
                                    //退出
                                    setTimeout(() => {
                                        this.$store.dispatch("Logout").then(() => {
                                            this.$router.push({ path: "login" });
                                        });
                                    }, 800);
                                }
                                //刷新 列表
                                _this.PageListUser();
                            }
                        })
                    },
                    onCancel () {
                    },
                });
            }
        },
        // 生成二维码
        creatQrCode () {
            let qrcode = new QRCode(this.$refs.qrCodeUrl, {
                text: this.entryUrl, // 需要转换为二维码的内容
                width: 100,
                height: 100,
                colorDark: "#000000",
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.H
            });
        },
        // 点击下载app二维码
        downloadQrCode (name) {
            var canvasData = document
                .getElementById("qrcode")
                .getElementsByTagName("canvas");
            var a = document.createElement("a");
            var event = new MouseEvent("click"); // 创建一个单击事件
            a.href = canvasData[0].toDataURL("image/png");
            a.download = "入职二维码";
            a.click(); // 触发a的单击事件
        },
        // 复制
        onCopy () {
            this.$copyText(this.entryUrl)
                .then(res => {
                    this.$message.success("复制成功！");
                })
                .catch(err => {
                    this.$message.error("抱歉，复制失败！");
                });
        }
    }
};
</script>
<style scoped>
    .form-inline label {
        justify-content: left !important;
    }
    .form-inline > .col {
        margin-bottom: 1.5rem !important;
    }
    .icons-list >>> .anticon {
        margin-right: 8px;
        font-size: 16px;
    }
    .ant-advanced-search-form {
        padding: 24px;
        background: #fbfbfb;
    }

    .ant-advanced-search-form .ant-form-item {
        display: flex;
        margin-bottom: 0px !important;
    }

    .ant-advanced-search-form .ant-form-item-control-wrapper {
        flex: 1;
    }

    #components-form-demo-advanced-search .ant-form {
        max-width: none;
    }
    #components-form-demo-advanced-search .search-result-list {
        margin-top: 16px;
        background-color: #fafafa;
        min-height: 200px;
        text-align: center;
        padding-top: 80px;
    }
    /* .crm-btn {
                                                                                                                      margin-left: 10px;
                                                                                                                      margin-bottom: 10px;
                                                                                                                    } */
    .organization {
        height: 36.5px;
        line-height: 36.5px;
        background: #eee;
        text-align: center;
        border-bottom: 1px solid #cacaca;
    }
</style>
<style lang="less">
    @import '~@/style/setting/inventory.less';
</style>
